package com.hopes.bizz.risk.transfer.handler;

import com.hopes.bizz.risk.control.entity.RiskMeasureTaskEntity;
import com.hopes.bizz.risk.control.entity.RiskMeasureTaskRecordEntity;
import com.hopes.bizz.risk.control.service.RiskMeasureTaskRecordService;
import com.hopes.bizz.risk.control.service.RiskMeasureTaskService;
import com.hopes.bizz.risk.transfer.bean.bo.RiskDataBo;
import com.hopes.bizz.risk.transfer.bean.dto.RiskMeasuresTaskRecordDto;
import com.hopes.bizz.risk.transfer.constant.RiskErrorType;
import com.hopes.bizz.risk.transfer.constant.RiskRequestType;
import com.hopes.bizz.risk.transfer.converter.RiskMeasuresTaskRecordConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author lyb
 * @version 1.0
 * @description: 任务记录
 * @date 2024/2/4 15:15
 */

@Component
@Slf4j
public class RiskMeasuresTaskRecordHandler extends AbstractRiskData<RiskMeasuresTaskRecordDto> {

    @Resource
    private RiskMeasureTaskService riskMeasureTaskService;

    @Resource
    private RiskMeasureTaskRecordService riskMeasureTaskRecordService;

    @Override
    protected void saveRiskData(RiskMeasuresTaskRecordDto riskMeasuresTaskRecordDto, RiskDataBo riskDataBo) {
        String taskUid = riskMeasuresTaskRecordDto.getCheckTaskId();
        RiskMeasureTaskEntity riskMeasureTask = riskMeasureTaskService.getByUid(taskUid);
        if (Objects.isNull(riskMeasureTask)) {
            saveErrorLog(riskMeasuresTaskRecordDto, riskDataBo, RiskErrorType.RISK_MEASURE_TASK_NOT_FOUND);
            return;
        }
        // 隐患排查记录不允许修改
        RiskMeasureTaskRecordEntity taskRecord = riskMeasureTaskRecordService.lambdaQuery()
                .eq(RiskMeasureTaskRecordEntity::getUid, riskMeasuresTaskRecordDto.getId())
                .one();
        if (Objects.nonNull(taskRecord)) {
            saveErrorLog(riskMeasuresTaskRecordDto, riskDataBo, RiskErrorType.RISK_MEASURE_TASK_RECORD_DISABLE_UPDATE);
            return;
        }
        RiskMeasureTaskRecordEntity taskRecordEntity = RiskMeasuresTaskRecordConverter.INSTANCE.toEntity(riskMeasuresTaskRecordDto);
        taskRecordEntity.setRiskUnitId(riskMeasureTask.getRiskUnitId());
        taskRecordEntity.setRiskEventId(riskMeasureTask.getRiskEventId());
        taskRecordEntity.setRiskControlId(riskMeasureTask.getRiskControlId());
        taskRecordEntity.setRiskCheckConfigId(riskMeasureTask.getId());
        taskRecordEntity.setOrgId(riskDataBo.getOrgId());
        riskMeasureTaskRecordService.save(taskRecordEntity);
    }

    @Override
    public RiskRequestType getRequestType() {
        return RiskRequestType.RISK_MEASURES_TASK_RECORD;
    }
}
